package bainuo

import com.alibaba.fastjson.JSON

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

def execute() {
    def conn
    def conn2
    try {
        // 初始化数据库连接
        conn2 = groovy.sql.Sql.newInstance(mypara.hqcon(1))
        conn = groovy.sql.Sql.newInstance(mypara.hqcon(2))

        // 获取当前日期时间并格式化
        def now = LocalDateTime.now()
        def formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
        def formattedDateTime = now.format(formatter)
        def selectSql = "select * from WMS_time where type = '物料档案' "
        def NOWtime = conn2.firstRow(selectSql)

        // 查询 bd_material 表
        def sql = "select pk_material, code, name, materialspec, pk_measdoc,pk_brand, pk_mattaxes, prodarea, def4, pk_marbasclass, memo, def3, def9, def7, def16,def17,creationtime, modifiedtime from bd_material where dr=0 and isnull(modifiedtime,creationtime) > ? and isnull(modifiedtime,creationtime) <= ?"
        // 获取 bd_material 表的数据
        def ckList = conn.rows(sql,[NOWtime.updateTime,formattedDateTime])


        processDataInBatches(ckList, 500, conn);

        // 插入时间记录
        def sqlTime = "UPDATE WMS_time set updateTime = ? where type = ?"
        conn2.execute(sqlTime, [ formattedDateTime,'物料档案'])
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (conn != null) {
            conn.close()
        }
        if (conn2 != null) {
            conn2.close()
        }
    }
}

// 按批次处理数据
def processDataInBatches(def data, int batchSize, def conn) {
    for (int i = 0; i < data.size(); i += batchSize) {
        // 获取当前批次的子列表
        List<String> batch = data.subList(i, Math.min(i + batchSize, data.size()));
        // 调用处理方法
        processBatch(batch, conn);
    }
}
def processBatch(def ckList, def conn){
    List<Map<String, Object>> items = new ArrayList<>()
    // 组装 JSON 数据
    for (def ckitem : ckList) {
        if (ckitem != null) {
            // 查询 bd_marbasclass 表
            def jldwList = conn.firstRow("select name from bd_measdoc where pk_measdoc = ?", [ckitem.pk_measdoc])

            // 查询 bd_marbasclass 表
            def wlflList = conn.firstRow("select name from bd_marbasclass where pk_marbasclass = ?", [ckitem.pk_marbasclass])

            // 查询 bd_materialtaxtype 表
            def slList = conn.firstRow("select mattaxesname from bd_mattaxes where pk_mattaxes = ?", [ckitem.pk_mattaxes])

            // 查询 bd_materialwarh 表
            def zdkuList = conn.firstRow("select safetystocknum from bd_materialplan where pk_material = ?", [ckitem.pk_material])

            // 查询 bd_materialconvert 表
            def flList = conn.rows("select pk_materialconvert, measrate, pk_measdoc, ispumeasdoc from bd_materialconvert where pk_material = ?", [ckitem.pk_material])

            //查询 bd_branddoc 表
            def cpList = conn.firstRow("select name from bd_branddoc where pk_brand = ?", [ckitem.pk_brand])

            Map<String, Object> item = new HashMap<>()
            item.put("id", ckitem.pk_material)
            item.put("mtrlNo", ckitem.code)
            item.put("mtrlName", ckitem.name)
            item.put("mtrlSpec", ckitem.materialspec)
            if (ckitem.def3 == "Y") {
                item.put("dmflag", 1)
            } else {
                item.put("dmflag", 0)
            }

            item.put("mtrlCateid", ckitem.pk_marbasclass)
            item.put("mtrlClass", wlflList?.name ?: "")  // 提供默认值
            item.put("nbMtrlName", ckitem.def16)  //公司内部名称
            item.put("cas", ckitem.def9)

            // 将百分数转换为小数
            def taxRate = slList?.mattaxesname?.replaceAll("%", "")?.toDouble()?.div(100) ?: 0.0
            item.put("mtrlTaxrate", taxRate)

            item.put("lowLimitWarningValue", zdkuList?.safetystocknum ?: 0)  // 提供默认值
            item.put("storageConditions", ckitem.def7)
            item.put("formerName", ckitem.def17)
            item.put("unitId", jldwList.name)
            item.put("mtrlBrandmark", ckitem.prodarea)
            item.put("spProperty", ckitem.def4)
            item.put("fNote", ckitem.memo)
            item.put("creationtime",ckitem.creationtime);
            item.put("modifiedtime",ckitem.modifiedtime);
            item.put("manufacturerId", ckitem.pk_brand)
            item.put("manufacturer", cpList?.name ?: "")


            // 处理 corp 对象
            List<Map<String, String>> corps = new ArrayList<>()
            for (def flitem : flList) {
                if (flitem != null && flitem.pk_measdoc != null && !flitem.pk_measdoc.toString().trim().isEmpty()) {
                    Map<String, String> corp = new HashMap<>()
                    // 将 measrate 从 "x/y" 格式的字符串转换为浮点数
                    String[] parts = flitem.measrate.toString().split('/')
                    double numerator = Double.parseDouble(parts[0])
                    double denominator = Double.parseDouble(parts[1])
                    double CmtrlAddRate = numerator / denominator

                    corp.put("id", flitem.pk_materialconvert.toString())
                    corp.put("cmtrlAddRate", CmtrlAddRate)

                    // 查询 bd_measdoc 表，确保传入正确的类型
                    def jlList = conn.firstRow("select name from bd_measdoc where pk_measdoc = ?", [flitem.pk_measdoc.toString()])

                    corp.put("cmtrlAddUnitId", jlList.name)  // 提供默认值

                    if (flitem.ispumeasdoc == "N") {
                        corp.put("defaultFlag", "0")  // 确保 defaultFlag 是字符串
                    } else if (flitem.ispumeasdoc == "Y") {
                        corp.put("defaultFlag", "1")
                    } else {
                        corp.put("defaultFlag", flitem.ispumeasdoc)
                    }

                    corps.add(corp)
                }
            }

            item.put("corps", corps)  // 将 corps 列表添加到 item 中
            items.add(item)
        }
    }

// 准备最终的数据结构
    Map<String, List> pushData = new HashMap<>()
    pushData.put("items", items)

// 调用 push 方法
    push(pushData)
}

def push(item){
    HQMHttpUtil.httpFWToMap("http://10.1.1.226:8099/wsdsjmcloud-v12/wbs/funcexe3/WMS_wuliaodangan001", item)
}
class HQMHttpUtil {
    public static HashMap<String, Object> account = new HashMap<String, Object>();

    public HQMHttpUtil() {
    }

    public HQMHttpUtil(HashMap<String, Object> account) {
        this.account = account;
    }
    public static Map httpFWToMap(String url, Map mapdata) {
        String json = JSON.toJSONString(mapdata);
        println "请求JSON"
        println json
        //PrintWriter out = null;
//        DataOutputStream out
        OutputStream out
        BufferedReader ins = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
            // 设置通用的请求属性
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("connection", "Keep-Alive");

            conn.connect();

            out = conn.getOutputStream();
            if (!"".equals(json)) {
                //out.writeBytes(json);
                out.write(json.getBytes("UTF-8"));
            }
            out.flush();
            out.close();


            // 定义BufferedReader输入流来读取URL的响应
            //            ins = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            if (conn.getResponseCode() == 200) {
                ins = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            } else {
                ins = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
            }

            String line;
            while ((line = ins.readLine()) != null) {
                result += line;
            }
            println("调用WMS返回报文="+result)
            return JSON.parseObject(result, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("[POST请求]向地址：" + url + " 发送数据：" + json + " 发生错误!" + result + "JSON结束");
        } finally {// 使用finally块来关闭输出流、输入流
            try {
                if (out != null) {
                    out.close();
                }
                if (ins != null) {
                    ins.close();
                }
            } catch (IOException ex) {
                System.out.println("关闭流异常");
            }
        }
        return null;
    }
}